package com.lx.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lx.annotation.CheckPermission;
import com.lx.entity.Order;
import com.lx.entity.OrderDetail;
import com.lx.entity.Product;
import com.lx.service.OrderService;
import com.lx.service.ProductService;
import com.lx.util.JwtUtil;
import com.lx.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 2025/9/17 9:47
 * author: 向远洋
 */
@RestController
@RequestMapping("/api")
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    ProductService productService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @PostMapping("/order/all")
    @CheckPermission({"1", "0"})
    public Result getAllOrder(@RequestBody Map<String, Object> params) {
        if(params.containsKey("isPay") && Integer.parseInt(params.get("isPay").toString()) == -2) {
            params.remove("isPay");
        }
        return Result.success(5200, "获取order - pageInfo成功").add("pageInfo", orderService.getPageInfo(params));
    }


    @CheckPermission(value = {"0", "1"})
    @PostMapping("/order/car")
    public Result getOrderCar(HttpServletRequest request) throws JsonProcessingException {
        String token = request.getHeader("Authorization");
        if(token == null || "".equals(token)) return Result.error(5500, "用户未登录，无法使用购物车！");
        Integer userId = JwtUtil.getUserID(token);
        return Result.success(5200, "获取购物车订单成功！").add("orderList", orderService.getOrderCarRecent(userId));
    }

    /**
     * 修改redis中的购物车订单
     * @param order
     * @param request
     * @return
     */
    @CheckPermission(value = {"0", "1"})
    @PostMapping("/order/modify")
    public Result modifyOrderCar(@RequestBody Order order, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Integer userId = JwtUtil.getUserID(token);
        orderService.modifyRedisOrderCar(order);
        ObjectMapper mapper = new ObjectMapper();
        try {
            stringRedisTemplate.opsForValue().set(userId + "orderCar", mapper.writeValueAsString(Collections.singletonList(order)));
            //没结算之前不需要保存到数据库
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return Result.success(5200, "修改购物车订单信息成功");
    }

    //提交购物车订单，将之前的购物车订单进行修改，改成用户可以查看的订单
    @CheckPermission(value = {"0", "1"})
    @PostMapping("/order/submit")
    public Result submitOrderCar(@RequestBody Order order) {
        //1.完善order，前端会返回一个较为完整的order【除了order.getOrderDetailList和order.getSerialNumber】
        //1.1数据库生成所有订单明细
        for (OrderDetail orderDetail : order.getOrderDetailList()) {
            orderDetail.setCost(orderDetail.getCost().multiply(new BigDecimal(orderDetail.getQuantity())));
        }
        orderService.addOrderDetailList(order);
        //1.2随机生成一个serialNumber,并更新数据库
        order.setIsPay(0); //待支付
        order.setSerialNumber(UUID.randomUUID().toString().replace("-", ""));
        orderService.modifyDBOrderCar(order);
        //最后删除redis中的购物车订单，创建一个限时15min的订单
        stringRedisTemplate.delete(order.getUserId() + "orderCar");
        stringRedisTemplate.opsForValue().set(order.getId() + "_" + order.getUserId() + "orderPaying", order.getId().toString(), 15, TimeUnit.MINUTES);
        return Result.success(5200, "提交购物车订单成功！");
    }

    @CheckPermission(value = {"0", "1"})
    @PostMapping("/order/easy")
    public Result getEasyOrderById(@RequestBody Map<String, Object> params) { //获取简易版本订单，不包括订单详情
        return Result.success(5200, "根据id获取订单成功").
                add("order", orderService.getEasyOrderById(Integer.parseInt(params.get("id").toString())));
    }


    @CheckPermission(value = {"0", "1"})
    @PostMapping("/order/close")
    public Result closeOrder(@RequestBody Map<String, Object> params) { //获取简易版本订单，不包括订单详情
        Integer orderId = Integer.parseInt(params.get("orderId").toString());
        orderService.modifyOrderStatusById(orderId, -1);
        List<OrderDetail> orderDetailList = orderService.getOrderDetailList(Collections.singletonList(orderId));
        for (OrderDetail orderDetail : orderDetailList) {
            //恢复es和数据库
            Product p = productService.getProductById(orderDetail.getProductId());
            p.setStock(p.getStock() + orderDetail.getQuantity());
            productService.updateProduct(p); //同步es + 异步数据库
        }
        return Result.success(5200, "订单关闭成功");
    }

    @CheckPermission(value = {"0"})
    @PostMapping("/order/delete")
    public Result deleteOrder(@RequestBody Map<String, Object> params) { //获取简易版本订单，不包括订单详情
        Integer orderId = Integer.parseInt(params.get("orderId").toString());
        //删除所有订单详情 + 删除订单
        orderService.deleteOrder(orderId);
        return Result.success(5200, "订单删除成功");
    }
}
